<template>
  <div>
    <van-address-list
      v-model="chosenAddressId"
      :list="addressList"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      :add-button-text="route.query.isCart||route.query.goodsId?'生成订单':'新增地址'"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
// 收获地址相关接口
import { getAddressList } from "@/api/address";
import { useRouter, useRoute } from "vue-router";

let router = useRouter();
let route = useRoute();
//  默认选中地址的id
let chosenAddressId = ref("");
// 地址数组
let addressList = ref([]);
// 新增地址
let onAdd = () => {
  // 判断是从购物车页面来的 还是直接购买
  if(route.query.isCart){
    router.push(`/create-order?checkGoodsId=${route.query.checkGoodsId}&addressId=${chosenAddressId.value}`);
  }else if(route.query.goodsId){ //从商品详情页过来的
    router.push(`/create-order?goodsId=${route.query.goodsId}&addressId=${chosenAddressId.value}`);
  }
  else{
    router.push("/edit-address");
  }
  
};
// 编辑地址
let onEdit = (value) => {
  router.push(`/edit-address?id=${value.id}`);
};
// 组件生命周期
onMounted(async () => {
  //后端返回该用户所有的地址
  //对新用户没有地址的处理
  let res = (await getAddressList({ limit: 100, page: 1 })).list || [];
  // 找出默认地址
  let resItem = res.find((item) => item.is_default == 1);
  chosenAddressId.value = resItem ? resItem.id : "";
  //改变后端数据字段  本质改造组件需要的数据  数组map方法 映射
  addressList.value = res.map((item) => {
    return {
      id: item.id,
      name: item.name,
      tel: item.phone,
      address: item.province + item.city + item.town + item.detail,
      isDefault: item.is_default == 1,
    };
  });
});
</script>

<style scoped lang="less">
</style>